/**
 * Module dependencies.
 */
var express = require('express')
,	path = require('path')
,	streams = require('./app/streams.js')();

var favicon = require('serve-favicon')
,	logger = require('morgan')
,	methodOverride = require('method-override')
,	bodyParser = require('body-parser')
,	errorHandler = require('errorhandler');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(favicon(__dirname + '/public/images/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride());
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(errorHandler());
}

// routing
require('./app/routes.js')(app, streams);

var server = app.listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

var io = require('socket.io').listen(server);
/**
 * Socket.io event handling
 */
require('./app/socketHandler.js')(io, streams);

var config = (function () {
  var fs = require('fs');
  var path = require('path');
  var ini = require('ini');
  var _ = require('lodash');

  var root = process.cwd();
  var iniPath = path.join(root, 'node-stun.ini');
  var config = {};
  try {
      config = ini.parse(fs.readFileSync(iniPath, 'utf-8'));
  } catch (e) {
      if (e.code === 'ENOENT') {
          console.warn('Config file not found:', e);
      } else {
          throw e;
      }
  }
  var defaults = {
      primary: {
          host: '127.0.0.1',
          port: '3478'
      },
      secondary: {
          host: '127.0.0.2',
          port: '3479'
      }
  };

  return _.defaultsDeep(config, defaults);
})();



var stun = require('./stun/stun');
var server = stun.createServer(config);

// Set log event handler
server.on('log', function (log) {
  console.log('%s : [%s] %s', new Date(), log.level, log.message);
});

// Start listening
server.listen();

